const {
    envList
} = require('../../envList.js');
const db = wx.cloud.database(); //使用API获取数据库的连接，该句执行完成后，db就代码远程的数据库
const app = getApp(); //获取小程序本身
let itemHeight = 310; //单菜品显示高度
Page({
    data: {
        active: "1", //当前选中态
        tops: [], //存储当前分类菜单高度信息
        menuHeight: 0,
        shoplistScollTop:0,
        deskId: 1,
        types: [],
        goods: [], //第一次从云上合出来的原始数据，这个数据不变
        tempGoods: [], //页面中真正显示的菜品数据
        cart: [], //购物车
        goodsCount: 0,
        height: 0,
        tempHeight: 0
    },
    onReady() {
        this.popupBox = this.selectComponent("#popupBox");
    },
    onLoad() { //为了效率，本地只在装载程序的时候，执行一次获取数据的操作。
        db.collection('types').get().then(resp => {
            this.setData({
                types: resp.data
            });
        }).catch(error => {
            console.error(error.errMsg);
        });
        db.collection('goods').orderBy('typeId', 'asc').get()
            .then(resp => {
                let size = resp.data.length;
                this.setData({
                    goods: resp.data,
                    tempGoods: resp.data,
                    height: size * itemHeight + 55,
                    tempHeight: size * itemHeight + 55
                });
            })
            .catch(error => console.log(error.errMsg));
        let _self = this;
        let winHeight = wx.getSystemInfoSync().windowHeight; //获取设备信息，windowHeight为可使用窗口调度，窗⼝⾼度，即：屏幕⾼度(screenHeight) - 导航(tabbar)⾼度。
        _self.setData({
            menuHeight: winHeight - 140
        });
        setTimeout(() => {
            let selectQuery = wx.createSelectorQuery(); //创建节点查询器
            //获取各类菜品，在页面中的高度信息
            selectQuery.selectAll(".shop-list__item").boundingClientRect().exec(res => {
                var arr = [];
                res[0].forEach((item, index) => {
                    0 === index ? arr.push(item.height) : arr.push(item.height + arr[index - 1]);
                });
                _self.setData({
                    tops: arr
                });
            });
        }, 1000); //延时获取节点的位置参数
    },
    //点击左侧分类绑定方法
    handleGroupSelect: function (event) {
        //获取当前分类数组中索引信息,以便根据index索引查询数据
        let _index = event.currentTarget.dataset.index;
        let _data = this.data;
        let _tops = _data.tops;
        //动画效果
        let oldTop = _data.shoplistScollTop;    //滚动条当前高度
        let newTop = _tops[_index-1] || 0;      //滚动条新高度
        if(oldTop<newTop){//向下
            let scrollNum = (newTop-oldTop)/10;
            let intervalId = setInterval(()=>{
                oldTop+=scrollNum;
                if(oldTop<newTop){
                    this.setData({shoplistScollTop:oldTop,active: _index + 1});
                }else{
                    clearInterval(intervalId);
                }
            });
        }else{ //向上
            let scrollNum = (oldTop-newTop)/10;
            let intervalId = setInterval(()=>{
                oldTop-=scrollNum;
                if(newTop<oldTop){
                    this.setData({shoplistScollTop:oldTop,active: _index + 1 });
                }else{
                    clearInterval(intervalId);
                }
            });
        }
        /*
        this.setData({
            active: _index + 1,
            shoplistScollTop: _tops[_index - 1] || 0
        });*/
    },
    //商品滚动事件绑定方法
    shopListScroll(event) {
        let _detail = event.detail;
        let _scrollTop = _detail.scrollTop; //滚动条距离顶部的距离
        let _deltaY = _detail.deltaY; //滚动条的滚动距离
        let _data = this.data;
        let _active = _data.active;
        let _tops = _data.tops;
        //通过判断_deltaY的正负，可以获取滚轮的滚动方向。正值为向上，负值为向下。
        if (_deltaY > 0) { //向上
            for (let i = _active - 1; i >= 0; i -= 1) {
                _scrollTop < _tops[i] && _scrollTop > (_tops[i - 1] || 0) && this.setData({
                    active: i + 1
                });
            }
        } else { //向下
            for (let i = _active - 1; i < _tops.length - 1; i += 1) {
                //当滚动条距离顶部的值>某个菜品集的高度且小下一个菜品集的高度时，active+2
                _scrollTop > _tops[i] && _scrollTop < _tops[i + 1] && this.setData({
                    active: i + 2
                });
            }
        }
    },
    searchOperation(event) {
        let key = '.*' + event.detail.value;
        db.collection("goods").where({
            name: {
                $regex: key,
            }
        }).get().then(res => {
            this.setData({
                tempGoods: res.data
            });
        });
    },
    selectGoods(event) {
        let id = event.currentTarget.dataset.id;
        let parameter = {
            "id": id
        };
        let currentItem = this.data.tempGoods.filter(item => item.id == id)[0];
        parameter.imageUrl = currentItem.imageUrl;
        parameter.name = currentItem.name;
        parameter.real = currentItem.real;
        parameter.id = currentItem.id;
        parameter.typeId = currentItem.typeId;
        parameter.check = currentItem.check;
        //优化用户操作步骤，省略了用户点击加号，加菜的操作
        if (currentItem.number == 0) {
            parameter.number = 1;
        } else {
            parameter.number = currentItem.number;
        }
        this.popupBox.switch(parameter);
    },
    navigateOperaion() {
        let date = new Date(); //生成一个时间信息
        let orderTime = `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
        app.globalData.orderTime = orderTime;
        app.globalData.deskId = this.data.deskId;
        app.globalData.cart = this.data.cart;
        wx.navigateTo({
            url: `../order/order`
        })
    },
    setShoppingCart(event) {
        let _self = this;
        let tempArrays = this.data.cart;
        let tempGoodsArrays = this.data.tempGoods //创建一个临时数组
        let currentGoods = event.detail;
        //设置购物车中的数据
        if (this.data.cart.find(element => element.id == currentGoods.id)) {
            let current = tempArrays.filter(element => element.id == currentGoods.id)[0];
            //number不可能的小于0，这里只能是大于0或者等于0。
            if (currentGoods.number > 0) { //此时说明菜品还在购物车里，只是数量发生了变化
                current.number = currentGoods.number;
            } else { //这意味着购物车中已经没有这个菜品了，所以要进行对应删除操作
                tempArrays.splice(tempArrays.findIndex(element => element.id == currentGoods.id), 1);
                tempGoodsArrays.find(element => element.id == currentGoods.id).number = 0; //删角标
            }
        } else if (currentGoods.number != 0) { //如果添加的菜品的number==0，则说明添加之后有删除了，所以不应该加入
            tempArrays.push(event.detail); //往购物车中追回数据
        }
        this.setData({
            cart: tempArrays,
            tempGoods: tempGoodsArrays
        });
        //往tempGoods中回写选择菜品的数量
        tempArrays.forEach(goods => {
            tempGoodsArrays.filter(item => item.id == goods.id).forEach(item => {
                item.number = goods.number;
            });
        });
        this.setData({
            tempGoods: tempGoodsArrays
        });
        //计算菜品总数，使用reduce()函数实现一个累加操作
        let count = this.data.cart.reduce((pre, current) => pre + current.number, 0);
        this.setData({
            goodsCount: count
        });
        //为types数组添加已选菜品数量
        this.data.types.forEach(element => element.number = 0); //清空types中的数据。
        let tempTypes = this.data.types;
        this.data.cart.forEach(item => {
            tempTypes.filter(element => item.typeId == element.id).forEach(element => {
                element.number += item.number;
            });
        });
        this.setData({
            types: tempTypes
        });
    }
});